﻿using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using System.Web;
using SecurityClient;

namespace SecurityModule.Workflows
{
    class WFGetHomeCreateUser : SimpleWorkflow
    {
        public WFGetHomeCreateUser()
        {
            Verb = "GET";
            Path = "/Home/CreateUser";
        }

        public override void PreProcessImplementation(HttpContext context)
        {
            var tokenId = context.Request.QueryString["InvitationToken"];
            // verify token and add Email and ClientCode to Request.Form

            if (string.IsNullOrEmpty(tokenId))
            {
                AddToForm(context.Request, new Dictionary<string, string>
                    {
                        {"EXTERRMSG", "Missing invitation token"},
                    });
            }
            else
            {
                try
                {
                    //Anon is attempting to confirm their identity
                    var security = new SecurityServiceProxy();
                    var email = security.GetTokenFieldValue(tokenId, "EmailAddress") as string;
                    var clientCode = security.GetTokenFieldValue(tokenId, "ClientCode") as string;
                    if (string.IsNullOrEmpty(email) || string.IsNullOrWhiteSpace(clientCode))
                    {
                        AddToForm(context.Request, new Dictionary<string, string>
                            {
                                {"EXTERRMSG", "Invalid invitation token"},
                            });
                    }
                    else // token is verified
                    {
                        //inject ClientCode and EmailAddress
                        AddToForm(context.Request, new Dictionary<string, string>
                            {
                                {"Email", email},
                                {"ClientCode", clientCode},
                            });
                    }
                }
                catch (Exception exception)
                {
                    if (exception is PipeException || exception is EndpointNotFoundException)
                    {
                        AddToForm(context.Request, new Dictionary<string, string>
                            {
                                {"EXTERRMSG", SecurityServiceDownMsg}
                            });
                    }
                    else
                    {
                        AddToForm(context.Request, new Dictionary<string, string>
                            {
                                {"EXTERRMSG", exception.Message}
                            });
                    }
                }
            }

            //inject YubikeyOTP input using replace
            context.Response.Filter = new ReplaceFilter(context.Response.Filter,
                context.Response.ContentEncoding,
                content =>
                {
                    content = content.Replace("{{YubikeyOTP}}",
                                                @"<label class='control-label' for='YubikeyOTP'>Yubikey</label><input name='YubikeyOTP' type='text' class='form-control'>");
                    // the user should trust the sensitve information they provide in this page will never be visible to the app directly, all JS code (except for trusted sources) should be cleaned to prevent potential AJAX calls
                    //content = content.RemoveEventsAndScripts();
                    return content;
                }
            );
        }

        public override void PostProcessImplementation(HttpContext context)
        {
            // No post-processing
        }
    }
}
